package com.itWaiLong.Service.Impl;

import com.itWaiLong.AppException.AppException;
import com.itWaiLong.AppException.GlobalExceptionHandler;
import com.itWaiLong.Dao.Comment;
import com.itWaiLong.Mapper.CommentMapper;
import com.itWaiLong.Service.CommentService;
import com.itWaiLong.Utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    /**
     * 添加评论
     * @param comment
     * @return
     */
    public void add(Comment comment) {


        //判断评论的级数
        Integer parentId = comment.getParentId();
        if (parentId == null || parentId == 0) {
           comment.setParentId(null);
        }

        //判断是回复某人的评论还是自己评论
        Integer postId = comment.getPostId();
        if (postId == null || postId == 0) {
            comment.setPostId(null);
        }

        //获取用户id
        Map<String,Object> map = ThreadLocalUtil.getThreadLocal();
        int userId = (int) map.get("userId");

        //设置评论者的id
        comment.setUserId(userId);

        int result = commentMapper.add(comment);
        if (result < 0){
            throw new GlobalExceptionHandler(AppException.PING_LUN_SHI_BAI);
        }
    }

    /**
     * 查看评论
     * @return
     */
    public List<Comment> select() {
        List<Comment> parenComment = commentMapper.select();
        if(parenComment == null || parenComment.size() == 0){
            throw new GlobalExceptionHandler(AppException.MEI_YOU_SHU_JU);
        }
        return parenComment;
    }
}
